package ExecuteEngine;

import Const.RC;
import java.util.*;

public class CrossProduct extends Operation{
	public Operation Op1;
	public Operation Op2;
	public Tuple t1;
	public Tuple t2;
	public Tuple t;
	public int mark = 0;
	public int start = 0;
	public List<String> titles;
	
	public CrossProduct(Operation o1, Operation o2){
		this.Op1 = o1;
		this.Op2 = o2;
		this.type = Operation.CROSSPRODUCT;
	}
	
	public RC.rc Open(){
		if(Op1.Open() != RC.rc.SUCCESS)
			return RC.rc.UNSUCCESS;
		if(Op2.Open() != RC.rc.SUCCESS)
			return RC.rc.UNSUCCESS;
		
		titles = Op1.GetTitles();
		List<String> t2 = Op2.GetTitles();
		for(int i=0; i<t2.size(); i++)
			titles.add(t2.get(i));
		
		return RC.rc.SUCCESS;
	}
	
	public boolean hasNext(){
		if(start == 0){
			if(Op1.hasNext() == false)
				return false;
			
			if(Op2.hasNext() == false)
				return false;
		}
		else{
			if(Op2.hasNext() == false){
				if(Op1.hasNext() == false)
					return false;
				
				Op2.Close();
				Op2.Open();
				
				if(Op2.hasNext() == false)
					return false;
				
				mark = 1;
			}
		}
		
		return true;
	}
	
	public Tuple GetNext()
	{
		t2 = Op2.GetNext();
		
		if(start == 0 || mark == 1){
			t1 = Op1.GetNext();
			mark = 0;
			start = 1;
		}
		
		t = new Tuple(t1);
		t.addTuple(t2);
		
		return t;
	}
	
	public void Close(){
		Op1.Close();
		Op2.Close();
	}
	
	public List<String> GetTitles(){
		return titles;
	}
}
